package com.fll.server.web;

import com.fll.server.web.exception.ContextException;
import io.netty.handler.codec.http.FullHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author fanlei
 * @version 1.0
 * @date 2019年01月25日
 */
public class ApiRoute {
    private static Logger logger = LoggerFactory.getLogger(ApiRoute.class);
    private static Map<String, RequestHandler> routes = new ConcurrentHashMap();
    private static List<RequestMiddleware> middlewares = new ArrayList();

    public ApiRoute() {
    }

    public static void addRoute(String uri, RequestHandler requestHandler) {
        if (routes.containsKey(uri)) {
            throw new IllegalArgumentException("Duplicate uri:" + uri);
        } else {
            logger.info("add route {}", uri);
            routes.put(uri, requestHandler);
        }
    }

    public static void addMiddleware(RequestMiddleware requestMiddleware) {
        if (middlewares.contains(requestMiddleware)) {
            throw new IllegalArgumentException("Duplicate RequestMiddleware:" + requestMiddleware);
        } else {
            logger.info("add requestMiddleware {}", requestMiddleware);
            middlewares.add(requestMiddleware);
        }
    }

    public static ResponseInfo run(FullHttpRequest request) {
        try {
            Iterator i$ = middlewares.iterator();

            while(i$.hasNext()) {
                RequestMiddleware middleware = (RequestMiddleware)i$.next();
                middleware.preRequest(request);
            }

            URI uri = new URI(request.getUri());
            RequestHandler handler = (RequestHandler)routes.get(uri.getPath());
            ResponseInfo responseInfo = null;
            if (handler != null) {
                responseInfo = handler.request(request);
            } else {
                responseInfo = ResponseInfo.build(40400, "api not found");
            }

            return responseInfo;
        } catch (Exception var4) {
            if (var4 instanceof ContextException) {
                return ResponseInfo.build(((ContextException)var4).getCode(), var4.getMessage());
            } else {
                logger.error("request error", var4);
                return null;
            }
        }
    }
}